//
//  UploadImageTool.swift
//  Exam-iOS
//
//  Created by lishengfeng on 2018/3/11.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import Foundation
import RxSwift
import RxCocoa
import UIKit


class UploadImageTool {
    
    let disposeBag = DisposeBag()
    
    var image: UIImage
    var resultHandle: (String?) -> Void
    
    private var uploadModel: ImageUploadModel?
    
    init(image: UIImage, resultHandle: @escaping ( (String?) -> Void ) ) {
        self.image = image
        self.resultHandle = resultHandle
    }
    
    ///循环引用，防止自动Release掉
    fileprivate var selfReference: UploadImageTool?
    
    
    deinit {
        
    }
    public func upload() {
   
        selfReference = self
        
        uploadModel = ImageUploadModel.fetch()
        if uploadModel == nil {
            
            //获取上传图片信息
            getUploadInfo()
        }
        else {
            //检查过期时间
            if let dateStr = uploadModel?.expiration {
                let formatter = DateFormatter()
                formatter.dateFormat = "yyyy-MM-ddThh:mm:ssZ"
                let date = formatter.date(from: dateStr)
                let nowDate = Date()
                let result = date?.compare(nowDate)
                
                ///在有效期内
                if result == ComparisonResult.orderedDescending {
                    ///直接上传图片
                    uploadImage()
                }
                else {
                    ///过期，重新获取上传图片信息
                    getUploadInfo()
                }
                
            }
            else {
                getUploadInfo()
            }
        }
    }
    
    ///获取上传图片信息
    private func getUploadInfo() {
        shurenProvider.rx
            .request(.getUploadUrl)
            .asObservable()
            .mapRespnseToObject(type: ImageUploadModel.self)
            .subscribe(onNext: { [weak self] (uploadModel) in
                self?.uploadModel = uploadModel
                uploadModel.storage()
            }, onError: { [weak self] (error) in
                showError(error)
                self?.selfReference = nil
            }, onCompleted: { [weak self] in
                self?.uploadImage()
            }).disposed(by: disposeBag)
    }
    
    ///上传图片
    private func uploadImage() {
        let dic = uploadModel?.dic()
        AliyunUploadImage.uploadImage(self.image, withImageUpload: dic) { [weak self] (result) in
            self?.resultHandle(result!)
            self?.selfReference = nil
        }
    }
}
